package pack

import (
	"git.gz.internal.jumaiyx.cn/pkg/tnet/buffer"
	"time"
)

type Protocol string

const (
	TCP Protocol = "TCP"
	UDP Protocol = "UDP"
)

const (
	FieldLength  = 4 // 头标长度的字节数
	IdLength     = 4 // ID长度的字节数
	UserIdLength = 8 // 用户id长度
	TimesLength  = 8
)

type IMessage interface {
	GetData() []byte
	GetLen() int
	GetMsgId() uint32
	GetUserId() uint64
}
type message struct {
	len      int
	data     []byte
	msgId    uint32
	totalLen int
	userID   uint64
	times    uint64 // 协议时间戳
}

func NewMessage(data []byte, n Protocol) IMessage {
	switch n {
	// 协议ID(CMD)＋ 用户id＋ 时间戳+ Encrypt(proto)=>int32(4)+int64(8)+int64（8)+byte[x]
	case UDP:
		if len(data) < IdLength+UserIdLength+TimesLength {
			return nil
		}
		return &message{
			len:      len(data[IdLength+UserIdLength+TimesLength:]),
			totalLen: len(data),
			data:     data[IdLength+UserIdLength+TimesLength:],
			msgId:    buffer.ByteOrder.Uint32(data[:IdLength]),
			userID:   buffer.ByteOrder.Uint64(data[IdLength : IdLength+UserIdLength]),
			times:    buffer.ByteOrder.Uint64(data[IdLength+UserIdLength : IdLength+UserIdLength+TimesLength]),
		}
	case TCP:
		if len(data) < IdLength+FieldLength {
			return nil
		}
		return &message{
			len:      int(buffer.ByteOrder.Uint32(data[:IdLength])),
			totalLen: len(data),
			data:     data[IdLength+FieldLength:],
			msgId:    buffer.ByteOrder.Uint32(data[IdLength : IdLength+FieldLength]),
			times:    uint64(time.Now().Unix()),
		}
	}
	return nil
}

func (message *message) GetData() []byte {
	return message.data
}

func (message *message) GetLen() int {
	return message.len
}

func (message *message) GetMsgId() uint32 {
	return message.msgId
}

func (message *message) GetUserId() uint64 {
	return message.userID
}
